﻿using BaseUtils.Helper;
using BaseUtils.Utils;
using NW_WEB_Service.App.Interface;
using NW_WEB_Service.App.Services;
using NW_WEB_Service.com.app.entities.modal;
using Service.src.com.utils.modal;
using Service.src.NW.Model;
using Service.src.NW.Model.UserPageProject;
using System.Collections.Generic;
using System.IO;
using System.Web.Http;
using System.Web.Http.Description;

namespace NW_WEB_Service.App.Controllers
{
    [RoutePrefix("api/project")]
    public class ProjectController : ApiController
    {
        public static ProjectInterface ProjectServer;
        //public static UserPageProjectServer ProjectServer;
        /// <summary>
        /// 查找项目
        /// </summary>
        /// <returns></returns>
        public ProjectController()
        {
            ProjectServer = new ProjectService();
            //ProjectServer = new UserPageProjectServer();
        }

        [HttpGet]
        [Route("{Id:int}")]
        public HttpResult Get(int Id)
        {
            ProjectEntity project = ProjectServer.Get(Id);
            HttpResult Coms = GetComponents(Id);
            if (Coms?.Data!=null)
            {
                project.Components = Coms.Data.ToString();
            }
       

            return new HttpResult().Success(project);
        }

        /// <summary>
        /// 查找项目
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("list")]
        [ResponseType(typeof(HttpResult))]
        public HttpResult SearchProject()
        {
            List<ProjectEntity> projects = ProjectServer.GetList();

            return new HttpResult().Success(projects);
        }

        /// <summary>
        /// 发布项目
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("released/{Id:int}")]
        public HttpResult ReleasedProjectById(int Id)
        {
            HttpResult Result = new HttpResult();
            ProjectEntity Project = ProjectServer.Released(Id);
            if (Project == null)
            {
                Result.Error("找不到产品，请确认");
            }
            else
            {
                Result.Success(Project);
            }
            return Result;
        }

        [HttpDelete]
        [Route("{Id:int}")]
        public HttpResult DeleteProject(int Id)
        {
            return new HttpResult().Success(ProjectServer.Delete(Id));
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="Project"></param>
        /// <returns></returns>
        [HttpPost]
        [Route]
        public HttpResult Add([FromBody] ProjectDTO Project)
        {
            ProjectEntity PE = new ProjectEntity();
            PE.Title = Project.Title;
            PE.Released = false;

            PE = ProjectServer.Install(PE);
            return new HttpResult().Success(PE);
        }

        /// <summary>
        /// 更新项目
        /// </summary>
        /// <param name="ProjectJson"></param>
        /// <returns></returns>
        [HttpPut]
        [Route]
        public HttpResult UpdateProject([FromBody] ProjectEntity Project)
        {
            int count = ProjectServer.Update(Project);
            return new HttpResult().Success(Project);
        }

        /// <summary>
        /// 查看页面项目组件
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("components/{Id}")]
        public HttpResult GetComponents(int Id)
        {
            string Path = $"{AppData.RuntimeFlowDataViewDirectory + Id}\\{AppData.UserPage}default.{AppData.UserPageComponent}";
            string ComponentJson = FileHelper.ReadContent(Path);
            return new HttpResult().Success(ComponentJson);
        }

        [HttpPost]
        [Route("copy-project/{ProjectId}")]
        public HttpResult CopyProject(int ProjectId)
        {
            ProjectEntity Target = ProjectServer.CopyProject(ProjectId);
            string sourceFolderPath = $"{AppData.RuntimeFlowDataViewDirectory + ProjectId}";
            string destinationFolderPath = $"{AppData.RuntimeFlowDataViewDirectory + Target.Id}";
            CopyAllFilesInFolder(sourceFolderPath, destinationFolderPath);
            HttpResult Coms = GetComponents(ProjectId);
            string ComponentJson = Coms.Data+"";
            if (ComponentJson.Contains("\"id\":\"44\""))
            {
                ComponentJson = ComponentJson.Replace("\"id\":\"44\"", $"\"id\":{Target.Id}");
            }
            FileHelper.WriteContent($"{AppData.RuntimeFlowDataViewDirectory}//{Target.Id}//",
                   AppData.UserPage + "default.Component", ComponentJson);
            return new HttpResult().Success();
        }

        private void CopyAllFilesInFolder(string sourceFolderPath, string destinationFolderPath)
        {
            // 创建目标文件夹（如果不存在）
            Directory.CreateDirectory(destinationFolderPath);

            // 获取源文件夹下的所有文件
            string[] files = Directory.GetFiles(sourceFolderPath);

            foreach (string file in files)
            {
                // 获取文件名（包含扩展名）
                string fileName = Path.GetFileName(file);
                // 组合目标文件路径
                string destinationFilePath = Path.Combine(destinationFolderPath, fileName);
                // 复制文件
                File.Copy(file, destinationFilePath, true);
            }
        }
    }
}
